(function() {
	var app = angular.module('searchPageApp', [ 'ui.bootstrap' ]);
	app
			.controller(
					'searchPageController',
					function($http,$scope, $log, $uibModal,$filter) {
						$scope.insertComponent = {};
						$scope.deleteComponent = {};
						var controller = this;
						controller.parmater = {};
						this.dataList = [];
						this.queryCondition = {
							"userNo" : "",
							"userName" : "",
							"belong_to_reglon" : "",
							"belong_to_department" : "",
							"date" : "",
							"page" : 1,
							"size" : 10,
						};
						this.paginationInfo = {
							"maxSize" : 5,
							"totalPages" : 0,
							"totalElements" : 0
						};

						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							loadData();
						}

						// 跳转页数，回车事件
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}

						this.pageChanged = function() {
							loadData();
						}

						// 时间控件

						controller.queryCondition.date = new Date();

						controller.format = "yyyy-MM-dd";

						controller.altInputFormats = [ 'yyyy-M!-d!' ];

						controller.popup1 = {
							opened : false
						};

						controller.open1 = function() {
							controller.popup1.opened = true;
						};
						/*
						 * controller.dateOptions = { customClass :
						 * getDayClass,// 自定义类名 dateDisabled : isDisabled //
						 * 是否禁用 }
						 */
						var tomorrow = new Date();
						tomorrow.setDate(tomorrow.getDate() + 1);
						var afterTomorrow = new Date();
						afterTomorrow.setDate(tomorrow.getDate() + 1);
						$scope.events = [ {
							date : tomorrow,
							status : 'full'
						}, {
							date : afterTomorrow,
							status : 'partially'
						} ];

						// 为日期面板中的每个日期（默认42个）返回类名。传入参数为{date: obj1, mode: obj2}
						function getDayClass(obj) {
							var date = obj.date, mode = obj.mode;
							if (mode === 'day') {
								var dayToCheck = new Date(date).setHours(0, 0,
										0, 0);

								for (var i = 0; i < $scope.events.length; i++) {
									var currentDay = new Date(
											$scope.events[i].date).setHours(0,
											0, 0, 0);

									if (dayToCheck === currentDay) {
										return $scope.events[i].status;
									}
								}
							}
							return '';
						}
						// 设置日期面板中的所有周六和周日不可选
						function isDisabled(obj) {
							var date = obj.date, mode = obj.mode;
							return mode === 'day'
									&& (date.getDay() === 0 || date.getDay() === 6);
						}

						function getDayClass(data) {
							var date = data.date, mode = data.mode;
							if (mode === 'day') {
								var dayToCheck = new Date(date).setHours(0, 0,
										0, 0);

								for (var i = 0; i < $scope.events.length; i++) {
									var currentDay = new Date(
											$scope.events[i].date).setHours(0,
											0, 0, 0);

									if (dayToCheck === currentDay) {
										return $scope.events[i].status;
									}
								}
							}

							return '';
						}

						this.changeDate = function() {
						}
						// 完成全选全部选事件
						$("#check_all").click(
								function() {
									$(".check_item").prop("checked",
											$(this).prop("checked"));
								});
						// 选中单个元素，如果单个元素选择满了，那么第一个主元素也被选中
						$(document)
								.on(
										"click",
										".check_item",
										function() {
											if ($(".check_item:checked").length == $(".check_item").length) {
												$("#check_all").prop("checked",
														true);
											}
											if ($(".check_item:checked").length == 0) {
												$("#check_all").prop("checked",
														false);
											}
										});
	
						// 搜索事件
						this.search = function() {
							loadData();
						}

						// 重置事件
						this.reset = function() {
							$scope.controller.queryCondition = {};
							$scope.controller.queryCondition.date = new Date();
						}

						// 删除用户信息
						this.delUser = function() {
							var basePath = $scope.getAppBasePath();
							var empId = "";
							var empNo = "";
							$.each($(".check_item:checked"), function() {
								empId += $(this).parents("tr").find("td:eq(1)")
										.text()
										+ ",";
								empNo += $(this).parents("tr").find("td:eq(2)")
										.text()
										+ ",";
							})
							// 如果没有选中的话
							if (empId == "" || empNo == "") {
								alert("请选择要删除的用户");
								return;
							} else {
								deleteComponent = {
									"userNo" : null,
									"userName" : null
								};

								deleteComponent.userNo = empId;
								deleteComponent.userName = empNo;
								if (confirm("确认删除用户["
										+ deleteComponent.userName + "]吗?")) {
									// 删除后台调用
									$
											.ajax({
												type : "POST",
												url : basePath
														+ "/data/deleteUserInfo",
												dataType : "json",
												contentType : "application/json",
												data : JSON
														.stringify(deleteComponent),
												success : function(data) {
													alert("删除成功");
													loadData();
												}
											});

								}
							}
						}
						// 新增用户事件
						this.addUser = function() {
							$scope.insertComponent = {};
							var modalInstanceAdd = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/system.management/componentadd.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'addUserController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});

							modalInstanceAdd.result.then(function(result) {
								loadData();
							});
						}
						// 删除用事件
						$(document)
								.on(
										"click",
										".delete_btn",
										function() {
											var basePath = $scope
													.getAppBasePath();
											// INSERT参数定义
											deleteComponent = {
												"userNo" : null,
												"userName" : null
											};
											var deleteId = $(this)
													.parents("tr").find(
															"td:eq(1)").text();
											var deleteNo = $(this)
													.parents("tr").find(
															"td:eq(2)").text();
											deleteComponent.userNo = deleteId;
											deleteComponent.userName = deleteNo;
											if (confirm("确认删除[" + deleteNo
													+ "]吗?")) {
												// 删除后台调用
												$
														.ajax({
															type : "POST",
															url : basePath
																	+ "/data/deleteUserInfo",
															dataType : "json",
															contentType : "application/json",
															data : JSON
																	.stringify(deleteComponent),
															success : function(
																	data) {
																alert("删除成功");
																loadData();
															}
														});
											}
										});

						// 修改用户信息
						this.editUserInfo = function(data) {
							$scope.updateComponent = angular.copy(data) || {};
//							$scope.updateComponent.accountValidityPeriod = $filter('date')
//							($scope.updateComponent.accountValidityPeriod,'yyyy-MM-dd');
							$scope.updateComponent.accountValidityPeriod = new Date($scope.updateComponent.accountValidityPeriod);
							$scope.oldPassword = $scope.updateComponent.userPasswd;
							var modalInstanceUpdate = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/system.management/componentedit.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'editUserController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
							
							
							modalInstanceUpdate.opened.then(function(){//模态窗口打开之后执行的函数  
								   $scope.updateComponent.roleId = data.roleId;  //设置第2个为初始值；
			            
							}); 
							modalInstanceUpdate.result.then(function(result) {
								loadData();
							});

						}
						// 程序初期化
						this.init = function() {
							loadData();
							
							// 加载角色列表
							loadRoleList();
						}

						this.init();
						// 加载数据
						function loadData() {
							if ($(".check_item:checked").length == 0) {
								$("#check_all").prop("checked", false);
							}
							var basePath = $scope.getAppBasePath();
							// 参数获取
							controller.parmater.userNo = controller.queryCondition.userNo
									|| "";
							controller.parmater.userName = controller.queryCondition.userName
									|| "";
							controller.parmater.belongToReglon = controller.queryCondition.belong_to_reglon
									|| "";
							controller.parmater.belongToDepartment = controller.queryCondition.belong_to_department
									|| "";
							controller.parmater.AccountValidityPeriod = $filter('date')(controller.queryCondition.date
									|| "",'yyyy-MM-dd');
//							controller.parmater.AccountValidityPeriod = "";
							controller.parmater.page = controller.queryCondition.page;
							controller.parmater.size = controller.queryCondition.size;

							// 后台调用
							data = controller.parmater;
							 $.ajax({
							 type : "POST",
							 url : basePath + "/data/getUserInfo",
							 dataType : "json",
							 contentType : "application/json",
							 data : JSON
							 .stringify(controller.parmater),
							 success : function(data) {
							 var jsonResult = angular.fromJson(data);
							 controller.dataList = jsonResult.data;
							 controller.paginationInfo.totalPages = jsonResult.totalPages;
							 controller.paginationInfo.totalElements = jsonResult.totalElements;
							 //手动刷新
							 $scope.$apply();  
							 }
							 });

						}
						
						
						// 加载角色列表数据
						function loadRoleList() {
							var basePath = $scope.getAppBasePath();
							$.ajax({
								type : "POST",
								url : basePath + "/data/getRoleList",
								dataType : "json",
								contentType : "application/json",
								success : function(data) {
									controller.roleList = angular.fromJson(data);
								 //手动刷新
									$scope.$apply();  
								}
							});
						}

					})
			.controller(
					'addUserController',
					function($scope, $uibModalInstance, $http, $log,$filter) {
						$scope.save = function() {
							var basePath = $scope.getAppBasePath();
							// INSERT参数定义
							insertComponent = {
								"userNo" : "",
								"name" : "",
								"gender" : "",
								"belongToReglon" : "",
								"belongToDepartment" : "",
								"emai" : "",
								"telephone" : "",
								"userPasswd" : "",
								"accountValidityPeriod" : "",
								"adminId" : "",
								"roleId" : ""
							};
							insertComponent.accountValidityPeriod = new Date();
							// INSERT值获取
							insertComponent.userNo = $scope.$parent.insertComponent.userNo||"";
							insertComponent.userName = $scope.$parent.insertComponent.userName||"";
							insertComponent.gender = $scope.$parent.insertComponent.gender||"";
							insertComponent.belongToReglon = $scope.$parent.insertComponent.belongToReglon||"";
							insertComponent.belongToDepartment = $scope.$parent.insertComponent.belongToDepartment||"";
							insertComponent.emai = $scope.$parent.insertComponent.emai||"";
							insertComponent.telephone = $scope.$parent.insertComponent.telephone||"";
							insertComponent.roleId = $scope.$parent.insertComponent.role||"";
							if($scope.$parent.insertComponent.userPasswd == null || $scope.$parent.insertComponent.userPasswd ==''){
								alert("请填写密码");
								return;
							}
							insertComponent.userPasswd = hex_sha1($scope.$parent.insertComponent.userPasswd);
							insertComponent.accountValidityPeriod =$filter('date')(insertComponent.accountValidityPeriod,'yyyy-MM-dd');
							// 后台调用
							$.ajax({
								type : "POST",
								url : basePath + "/data/insertUserInfo",
								dataType : "json",
								contentType : "application/json",
								data : JSON.stringify(insertComponent),
								success : function(data) {
									$uibModalInstance.close();
									
									alert("插入成功");
								}
							});
							
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					})
			.controller(
					'editUserController',
					function($scope, $uibModalInstance, $http, $log,$filter) {
						$scope.save = function() {
							var basePath = $scope.getAppBasePath();
							// INSERT参数定义
							updateComponent = {
								"id" : "",
								"userNo" : "",
								"name" : "",
								"userPasswd" : "",
								"gender" : "",
								"belongToReglon" : "",
								"belongToDepartment" : "",
								"emai" : "",
								"telephone" : "",
								"AccountValidityPeriod" : "",
								"adminId" : "",
								"roleId" : ""
							};
							// UPDATE值获取
							updateComponent.id = $scope.updateComponent.id;
							updateComponent.userNo = $scope.updateComponent.userNo;
							updateComponent.userName = $scope.updateComponent.userName;
							updateComponent.gender = $scope.updateComponent.gender;
							updateComponent.belongToReglon = $scope.updateComponent.belongToReglon;
							updateComponent.belongToDepartment = $scope.updateComponent.belongToDepartment;
							updateComponent.emai = $scope.updateComponent.emai;
							updateComponent.telephone = $scope.updateComponent.telephone;
							updateComponent.roleId = $scope.$parent.updateComponent.roleId||"";
							if($scope.updateComponent.userPasswd == null || $scope.updateComponent.userPasswd ==''){
								alert("请填写密码");
								return;
							}
							if($scope.oldPassword == $scope.updateComponent.userPasswd){
								updateComponent.userPasswd="";	
							}else{
								updateComponent.userPasswd = hex_sha1($scope.updateComponent.userPasswd);
							}
							
							updateComponent.AccountValidityPeriod = $filter('date')($scope.updateComponent.accountValidityPeriod,'yyyy-MM-dd');
							
							if($scope.updateComponent.userPasswd == 'admin'){
								$scope.nowPassword =  hex_sha1($scope.updateComponent.userPasswd);
							}else{
								$scope.nowPassword = $scope.updateComponent.userPasswd;
							}
							// 后台调用
							$.ajax({
								type : "POST",
								url : basePath + "/data/updateUserInfo",
								dataType : "json",
								contentType : "application/json",
								data : JSON.stringify(updateComponent),
								success : function(data) {
									alert("更新成功");
								}
							});
							$uibModalInstance.close();
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					});
})();